package com.yunxun.coinmessage.controller;

import com.yunxun.coinmessage.entity.Program;
import com.yunxun.coinmessage.templatedata.MsgResult;
import com.yunxun.coinmessage.service.ProgramService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.List;

@Controller
public class ProgramController {
    @Autowired
    ProgramService programService;

    @RequestMapping("/queryAllProgram")
    public String queryAll(Model model){
        Integer total=programService.queryTotal();
        List<Program> programList= programService.queryAll();
        model.addAttribute("programList",programList);
        model.addAttribute("total",total);
        return "program-list";
    }


    @RequestMapping("/openAddProgramWindow")
    public String openAddprogramWindow(){
        return "program-add";
    }


    @RequestMapping("/openEditProgram")
    public String openEditProgram(Integer program_id,Model model) throws Exception{
        if(program_id==null){
           throw new Exception("发生错误");
        }
       Program program= programService.queryById(program_id);
       model.addAttribute("program",program);
       return "program-edit";
    }

    @RequestMapping("/addProgram")
    @ResponseBody
    public MsgResult addProgram(@Valid Program program, BindingResult result){
        if (result.hasErrors()) {
            List<ObjectError> list=result.getAllErrors();
         for(ObjectError error:list){
                return new MsgResult(false,error.getDefaultMessage());
        }

        }
         return programService.add(program);
    }

    /**
     * 修改栏目
     * @param program
     * @return
     */
    @RequestMapping("/editProgram")
    @ResponseBody
    public MsgResult editProgram(Program program){
        return programService.updateById(program);
    }

    @RequestMapping("/deleteProgramById")
    @ResponseBody
    public MsgResult deleteById(Integer program_id){
        return programService.deleteById(program_id);
    }
}
